package controllers;

import com.google.gson.JsonObject;
import constants.BuDefault;
import constants.Configurations;
import constants.Default;
import constants.TplPath;
import constants.system.MemberShip;
import constants.ws.PageBean;
import duppentity.Dupps;
import duppentity.dto.bu.BuDtoUtil;
import duppentity.dto.bu.CouponDto;
import duppentity.dto.bu.CouponUserDto;
import play.libs.WS;
import utils.RequestHelper;
import utils.StringUtil;
import utils.Utils;

import java.util.ArrayList;
import java.util.List;

/**
 * @author yangz
 * @desc 优惠券管理
 */
public class CouponController extends ApiController{

    public static void couponList(){
        String page = TplPath.couponList;
        if (Utils.exitFile(page)){
            renderTemplate(page);
        }
    }

    public static void getCouponList() {
        PageBean pageBean = PageBean.get();
        String name = params.get("name",String.class);
        Integer type = params.get("type",Integer.class);
        Integer use = params.get("use",Integer.class);
        JsonObject data = couponDupp.getCouponList(name,type,use,null,pageBean.getOffset(),pageBean.pageCount());
        if (!checkResult(data)) {
            apiError(data);
        }
        List<CouponDto> couponDtoList = BuDtoUtil.getCouponDtoList(data);
        apiList(data, couponDtoList);
    }


    public static void addCoupon(){
        String page = TplPath.addCoupon;
        if (Utils.exitFile(page)){
            renderTemplate(page);
        }
    }


    public static void editCoupon(){
        String page = TplPath.editCoupon;
        Long id = params.get("id",Long.class);
        JsonObject result = null;
        if (id>0) {
            result =couponDupp.getCoupon(id);
        }
        if (result!=null) {
            CouponDto couponDto = BuDtoUtil.getCouponDto(result);
            String path="";
            String qrUrl=Configurations.qrUrl;
            //如果是公开链并且没失效
            if (couponDto.dispatchType==0 && couponDto.invalid==0) {
                String url = Configurations.couponUrl.concat(couponDto.id);
                WS.WSRequest wsRequest=WS.url(url);
                if(wsRequest.get().getJson().isJsonObject()) {
                    JsonObject couponResult = wsRequest.get().getJson().getAsJsonObject();
                    if (!couponResult.isJsonNull()){
                        path = couponResult.get("result").getAsString();
                    }
                }else{
                    path = play.utils.Utils.urlDecodePath(wsRequest.get().getString());
                }

            }
            if (Utils.exitFile(page)) {
                renderTemplate(page,couponDto,path,qrUrl);
            }
        }
    }


    /**
     * 保存优惠券
     */
    public static void saveCoupon() {

        Long id = params.get("id", Long.class);

        String name = params.get("name", String.class);
        Integer totalCount = params.get("totalCount",Integer.class);
        Integer type = params.get("type",Integer.class);
        Integer val = params.get("val",Integer.class);
        if (val!=null && val>0){
            val = Utils.getIntPrice(Double.parseDouble(val.toString()));
        }
        Integer use = params.get("use",Integer.class);
        Integer limit = params.get("limit",Integer.class);
        if (limit!=null && limit==1){
             limit = params.get("limitCount",Integer.class);
             if (limit<=0 || limit>100){
                 apiError("限领1到100之间的整数");
             }
        }
        Integer validType = params.get("validType",Integer.class);
        
        Integer validDay = params.get("validDay",Integer.class);
        String startTime = params.get("startTime",String.class);
        String endTime = params.get("endTime",String.class);
        Integer dispatchType = params.get("dispatchType",Integer.class);

        MemberShip memberShip = MemberShip.current();
        if (id!=null && id > 0) {
            JsonObject data = couponDupp.editCoupon(memberShip.getSessionId(),memberShip.getId(),id, name, totalCount,MemberShip.current().getId());
            if (checkResult(data)) {
                if (data.get("result").getAsBoolean()) {
                    apiOk("修改优惠券成功");
                } else {
                    apiError("修改优惠券失败");
                }
            } else {
                apiError(data);
            }
        } else {
            JsonObject data = couponDupp.addCoupon(memberShip.getSessionId(),memberShip.getId(),name,totalCount,type,val,use,limit,validType,validDay,startTime,endTime,dispatchType,MemberShip.current().getId());
            if (checkResult(data)) {
                if (data.get("id").getAsLong() > 0) {
                    apiOk("保存优惠券成功");
                } else {
                    apiError("保存优惠券失败");
                }
            } else {
                apiError(data);
            }
        }
        
    }


    public static void updateInvalid() {
        Long id = params.get("id", Long.class);
        Integer invalid = params.get("invalid", Integer.class);
        if (id > 0) {
            JsonObject data = couponDupp.updateInvalid(MemberShip.current().getSessionId(), MemberShip.current().getId(),id,invalid, MemberShip.current().getId());
            if (checkResult(data)) {
                if (data.get("result").getAsBoolean()) {
                    apiOk("失效操作成功");
                } else {
                    apiError("失效操作失败");
                }
            } else {
                apiError(data);
            }
        }
    }

    public static void saveDispatchUser() {
        Long couponId = params.get("couponId", Long.class);
        String userIds = params.get("userIds", String.class);

        if (couponId > 0) {
            String[] strs=userIds.split(",");
            List<Long> getUserIds= new ArrayList<>();
            for (Integer i=0;i<strs.length;i++){
                if (StringUtil.isNumeric(strs[i])){
                    getUserIds.add(Long.parseLong(strs[i]));
                }
            }
            JsonObject data = couponDupp.saveDispatchUser(MemberShip.current().getSessionId(), MemberShip.current().getId(),couponId,getUserIds, MemberShip.current().getId());
            if (checkResult(data)) {
                if (data.get("result").getAsBoolean()) {
                    apiOk("派发优惠券成功");
                } else {
                    apiError("派发优惠券失败");
                }
            } else {
                apiError(data);
            }
        }
    }

    /**
     * 已领取优惠券
     */
    public static void receive(){
        Long id = params.get("id",Long.class);
        String page = TplPath.receive;
        if (Utils.exitFile(page)){
            renderTemplate(page,id);
        }
    }

    public static void getCouponUserList() {
        PageBean pageBean = PageBean.get();
        Long couponId = params.get("id",Long.class);
        Long userId = params.get("userId",Long.class);
        String mobile = params.get("mobile",String.class);
        Long dispatchUserId = params.get("dispatchUserId",Long.class);
        String startCreateTime = params.get("startCreateTime",String.class);
        String endCreateTime = params.get("endCreateTime",String.class);
        String startUseTime = params.get("startUseTime",String.class);
        String endUseTime = params.get("endUseTime",String.class);

        JsonObject data = couponDupp.getCouponUserList(userId,mobile,couponId,dispatchUserId,startCreateTime,endCreateTime,startUseTime,endUseTime,pageBean.getOffset(),pageBean.pageCount());
        if (!checkResult(data)) {
            apiError(data);
        }
        List<CouponUserDto> couponUserDtoList = BuDtoUtil.getCouponUserDtoList(data);
        apiList(data, couponUserDtoList);
    }



}
